<script setup lang="tsx">


import { onMounted, ref } from 'vue';

import { addRemoteProblem, getRemoteOJ, getRemoteProblemList, IRemoteOJ, IRemoteProblem } from '@/api/problem';
import { PaginationProps, TableProps } from 'tdesign-vue-next';
import { ProblemTagProps } from '@/components/Problem/ProblemTag.vue';
import message from 'ant-design-vue/es/message';
import { useRoute, useRouter } from 'vue-router';

const router = useRouter();
const route = useRoute();


const isLoading = ref<TableProps['loading']>(false);
const remote = ref<number>(0);
const currentOjName = ref<string>('');

const list = ref<IRemoteProblem[]>([]);
const data = ref<TableProps['data']>([]);

const pagination = ref<TableProps['pagination']>({
  defaultPageSize : 20,
  total: 0,
  defaultCurrent: 1,
  maxPageBtn: 100,
});



const onclickAdd = async (remoteId: string) => {
  const foundRow = data.value.find((row) =>  row.remoteId === remoteId);
  if( foundRow) {
    foundRow.isGetProblem = true;
    try {
      const ret = await addRemoteProblem(currentOjName.value + remoteId);
      if (ret) {
        foundRow.is_get_problem_success = true; // 如果请求成功，更新 is_get_problem_success
        message.success(`${remoteId} 添加成功`);
      } else {
        message.error(`添加 ${remoteId} 失败`);
      }
    } catch (error) {
      message.error(`添加 ${remoteId} 失败: ${ error.message }`);
    } finally {
      foundRow.isGetProblem = false; // 请求完成后设置为 false
    }
  } else {
    message.error(`找不到远程 ID 为 ${remoteId} 的题目`);
  }
};

const columns = ref<TableProps['columns']>([
  {
    title: '远程ID',
    colKey: 'remoteId',
    align: 'center',
    width: '100',
  },
  {
    title: '题目名称',
    colKey: 'name',
    align: 'center',
    width: '200',
    cell: (h, { row }) => {
      return <a href={row.remoteUrl} style="text-decoration:none;">{row.name}</a>;
    }
  },
  {
    title: '标签',
    colKey: 'tags',
    align: 'center',
    width: '400',
    cell: (h, { row }) => {
      return (
        <div>
          {
            row.tags.map((tag: ProblemTagProps) => {
              return <t-tag class="m-1" theme="primary">{tag.name}</t-tag>;
            })
          }
        </div>
      );
    },
  },
  {
    title: '难度',
    colKey: 'rating',
    align: 'left',
    sortType: 'all',
    sorter: true,
    width: '120',
    cell: (h, { row }) => {
      if (row.rating === 0 || row.rating === undefined) {
        row.rating = 0;
        return <t-tag theme="success" variant="light">未知</t-tag>;
      } else if (row.rating >= 2300) {
        return <t-tag theme="danger"> {row.rating} </t-tag>;
      } else if (row.rating >= 1400) {
        return <t-tag theme="warning"> {row.rating} </t-tag>;
      } else {
        return <t-tag theme="success"> {row.rating} </t-tag>;
      }
    },
  },
  {
    title: '通过人数',
    colKey: 'solvedCount',
    align: 'center',
    width: '120',
    sortType: 'all',
    sorter: true,
    cell: (h, { row }) => {
      if (row.solvedCount >= 6000) {
        return <t-tag theme="success"> {row.solvedCount} </t-tag>;
      } else if (row.solvedCount >= 1500) {
        return <t-tag theme="warning"> {row.solvedCount} </t-tag>;
      } else {
        return <t-tag theme="danger"> {row.solvedCount} </t-tag>;
      }
    },
  },
  {
    title: '操作',
    colKey: 'is_get_problem_success',
    align: 'center',
    width: '120',
    cell: (h, { row }) => {
      if (row.is_get_problem_success) {
        return <t-button theme="danger" variant="outline" disabled>已添加</t-button>;
      } else {
        return (
          <t-button theme="success" loading={row.isGetProblem} onclick={() => onclickAdd(row.remoteId)}>添加</t-button>
        );
      }
    },
  }
]);

const fetchRemoteProblemList = async (paginationInfo:PaginationProps) => {
  try {
    isLoading.value = true;

    const { current , pageSize } = paginationInfo;
    const res: {
      results: IRemoteProblem[],
      count: number,
      next: string,
      previous: string
    } = await getRemoteProblemList( current , pageSize , remote.value );

    pagination.value.total = res.count;
    list.value = res.results;
    let id = 1;
    data.value = list.value.map((problem) => ({
      index: id++,
      ...problem,
      isGetProblem: false,
    })) as unknown as TableProps['data'];

    isLoading.value = false;
  } catch (error) {
    message.error(`Error fetching problem list:${ error.message }`);
    isLoading.value = false;
  }
};

const rehandleChange: TableProps['onChange'] = (changeParams, triggerAndData) => {

};

const onPageChange: TableProps['onPageChange'] = async (pageInfo) => {
  console.log('page-change', pageInfo);
  isLoading.value = true;

  await fetchRemoteProblemList(pageInfo);
  const newQuery = { ...route.query, ...{ current: pageInfo.current, pageSize: pageInfo.pageSize } };
  router.push({ path: route.path, query: newQuery }, () => {}, { shallow: true });
  isLoading.value = false;
};


const fetchRemoteOJ = async (remote: number) => {
  const ret: IRemoteOJ = await getRemoteOJ(remote);
  currentOjName.value = ret.name;
};

onMounted(async () => {
  if (route.params.remote) {
    remote.value = Number(route.params.remote);
  }
  await fetchRemoteOJ(remote.value);
  await fetchRemoteProblemList({
    current: pagination.value.current || pagination.value.defaultCurrent,
    pageSize: pagination.value.pageSize || pagination.value.defaultPageSize,
  });
});


const sort = ref<TableProps['sort']>({
  sortBy: 'rating',
  descending: true,
});
const request = (sort: TableProps['sort']) => {
  // 模拟异步请求，进行数据排序
  if (Array.isArray(sort)) return;
  const timer = setTimeout(() => {
    if (sort) {
      data.value = data.value
      .concat()
      .sort((a, b) => (sort.descending ? b[sort.sortBy] - a[sort.sortBy] : a[sort.sortBy] - b[sort.sortBy]));
    } else {
      data.value = data.value.concat();
    }
    clearTimeout(timer);
  }, 100);
};
const sortChange: TableProps['onSortChange'] = (val) => {
  sort.value = val;
  request(val);
};


</script>

<template>

  <div style="display: flex; flex-direction: column">
    <nav aria-label="breadcrumb">
      <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="/admin/user">管理员设置</a></li>
        <li class="breadcrumb-item"><a href="/admin/problem-list/">题目管理</a></li>
        <li class="breadcrumb-item active"><a href="/admin/problem-add-from-remote/">远程题库</a>></li>
        <li class="breadcrumb-item active" aria-current="page"> {{ currentOjName }}</li>
      </ol>
    </nav>
    <h1 v-if="!isLoading" class="mt-4">{{ currentOjName }} 远程题目</h1>

    <t-space direction="vertical">
      <t-space align="center">
        <t-table
          row-key="index"
          :columns="columns"
          :loading="isLoading"
          :data="data"
          :sort="sort"
          :pagination="pagination"
          @page-change="onPageChange"
          @sort-change="sortChange"
          @change="rehandleChange"
          table-layout="auto">
        </t-table>
      </t-space>
    </t-space>
  </div>

</template>

<style scoped lang="less">

</style>
